package bll

import (
	"context"
	"maya-service/store/mysql"

	"maya-service/model"
	"maya-service/model/entity"
	"maya-service/model/mapping"
	"maya-service/store"
	"time"
)

type option struct {
	iOption store.IOption
}

var Option = &option{
	iOption: mysql.Option,
}

func init() {
	Register(Option)
}

func (a *option) init() func() {
	return func() {}
}

// Create
func (a *option) Create(ctx context.Context, in *model.OptionCreateRequest) (int64, error) {
	var (
		err error
		id  int64
	)
	c := buildOption(in)
	id, err = a.iOption.Create(ctx, c)
	return id, err
}

// Update
func (a *option) Update(ctx context.Context, in *model.OptionUpdateRequest) error {
	var (
		dict = make(map[string]interface{})
	)

	if in.TitleId != nil {
		dict["title_id"] = in.TitleId
	}

	if in.Image != nil {
		dict["image"] = in.Image
	}

	if in.Desc != nil {
		dict["desc"] = in.Desc
	}

	if in.CreatedAt != nil {
		dict["created_at"] = in.CreatedAt
	}

	if in.UpdatedAt != nil {
		dict["updated_at"] = in.UpdatedAt
	}

	if in.AnalysisText != nil {
		dict["analysis_text"] = in.AnalysisText
	}

	if in.AnalysisImg != nil {
		dict["analysis_img"] = in.AnalysisImg
	}

	// do other update here
	updateAt := time.Now().Unix()
	in.UpdatedAt = &updateAt
	return a.iOption.Update(ctx, in.Id, dict)
}

// Delete
func (a *option) Delete(ctx context.Context, in *model.OptionDeleteRequest) error {
	return a.iOption.Delete(ctx, in)
}

// List
func (a *option) List(ctx context.Context, in *model.OptionListRequest) (*model.OptionListResponse, error) {
	var (
		err   error
		total int
		list  []*entity.Option
		out   = &model.OptionListResponse{}
	)

	if total, list, err = a.iOption.List(ctx, in); err != nil {
		return nil, err
	}

	out.Total = total
	out.List = mapping.OptionsEntityToDto(list)

	return out, nil
}

// Find
func (a *option) Find(ctx context.Context, in *model.OptionInfoRequest) (*model.OptionInfo, error) {
	var (
		err  error
		data *entity.Option
		out  = &model.OptionInfo{}
	)

	if data, err = a.iOption.Find(ctx, in); err != nil {
		return nil, err
	}

	out = mapping.OptionEntityToDto(data)
	return out, nil
}

// buildOption build entity
func buildOption(in *model.OptionCreateRequest) *entity.Option {

	ety := &entity.Option{}

	ety.TitleId = in.TitleId

	ety.Image = in.Image

	ety.Desc = in.Desc

	ety.AnalysisImg = in.AnalysisImg

	ety.AnalysisText = in.AnalysisText

	ety.CreatedAt = time.Now().Unix()

	ety.UpdatedAt = in.UpdatedAt

	return ety
}
